package edu.cmu.aes.project2.security;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UISecurityUtil {
	
	public static Properties securityConfig;
	public static Map<String,String> loginMap; 
	
	static{
		init();
	}
	
	protected static void init(){		
		securityConfig = new SecurityProperties();
		
		loginMap = new HashMap<String,String>();
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return true if redirect is required
	 * @throws IOException
	 */
	public static boolean checkSecuredAccess(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		if(request.isSecure() == true)
			return false;
		
		String securedURL = securityConfig.getProperty("secured_url");
		if(securedURL == null){
			(new IOException("Secured URL properties not found")).printStackTrace();
			response.sendRedirect("error.jsp");
			return true;
		}
		
		securedURL = securedURL+request.getRequestURI();
		response.sendRedirect(securedURL);
		return true;
	}
	
	public static void registerLogin(HttpServletRequest request, String username){
		HttpSession session = request.getSession();
		String sessionId = request.getRequestedSessionId();
		loginMap.put(username,sessionId);
		session.setAttribute("username", username);
	}
	
	public static boolean unRegisterLogin(HttpServletRequest request){
		Object object = request.getSession().getAttribute("username");
		if(object == null)
			return false;
		
		String userName = (String) object;
		String sessionId = request.getRequestedSessionId();
		String sessionIdInMap = loginMap.get(userName);
		if(sessionId.equals(sessionIdInMap)){
			loginMap.remove(userName);
			request.getSession().removeAttribute("username");
			return true;
		}
		return false;
	}
	
	public static String getUserName(HttpServletRequest request){
		
		Object object = request.getSession().getAttribute("username");
		if(object == null)
			return null;
		
		String userName = (String) object;
		String sessionId = request.getRequestedSessionId();
		String sessionIdInMap = loginMap.get(userName);
		if(sessionId.equals(sessionIdInMap))
			return userName;
		
		return null;
	}
}
